package com.lw.controller;

import com.lw.entity.Resp;
import com.lw.service.impl.FileUploadServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("image")
public class IMController {
    @Resource
    private FileUploadServiceImpl fileUploadService;
    /**
     * 单图上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("upload")
    public Resp uploadImages(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
//        int req = fileUploadService.uploadImage(file,request);
//        if(req>0){
//            return new Resp(true,"成功插入"+req+"张图片");
//        }
//        图片转base64
        try {
            return new Resp(true, "data:image/png;base64,"+Base64.getEncoder().encodeToString(file.getBytes()));
        }
        catch (IOException e) {
            e.printStackTrace();
            return new Resp(true,"no");
        }

    }

    /**
     * 多图片上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("uploads")
    public Resp uploadImages(@RequestParam(value = "file") MultipartFile[] file, HttpServletRequest request){
        int req = fileUploadService.uploadImages(file,request);
        if(req>0){
            return new Resp(true, "成功插入"+req+"张图片");
        }
        return new Resp(true,"no");
    }

}
